package com.subtlman.logframework.queue;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Create: IntelliJ IDEA.
 * @Author: subtlman_ljx
 * @Date: 2022/11/18/15:54
 * @Description:
 */
@Controller
@RequestMapping("/buy")
public class BuyController {

    //线程安全的请求队列
    private static BuyQueue buyqueue = null;

    @PostMapping("/addOrders.do")
    @ResponseBody
    public Object addOrders(BuyRequest buyrequest) {
        //默认最大值 int MAX_VALUE = 0x7fffffff;
        LinkedBlockingQueue<Object> queue = new LinkedBlockingQueue<>();





        Map results = new HashMap<>();
        try {

            //下订单之前，先获取商品的剩余数量
            //这里面先采用定值的写法
            int residue = 3;
            //如果剩余数量不足，直接响应客户端“卖完了”
            if (residue < 1) {
                results.put("msg", "卖完了");
                results.put("done", false);
                System.out.println(results);
                return results;
            }

            //如果还有剩余商品,就准备将请求放到请求队列中
            //第一次初始化请求队列,队列的容量为当前的商品剩余数量
            if (buyqueue == null) {
                buyqueue = new BuyQueue(residue);
            }
            //当队列的可用容量大于0时,将请求放到请求队列中
            if (buyqueue.remainingCapacity() > 0) {
                buyqueue.put(buyrequest);
            } else {//当请求队列已满,本次请求不能处理,直接响应客户端提示请求队列已满
                results.put("msg", "抢购队列已满，请稍候重试！");
                results.put("done", false);
                return results;
            }
            //如果线程类的当前执行标志为未执行,即空闲状态,通过线程池启动线程
            if (!DealQueueThread.excute) {
                DealQueueThread dealQueue = new DealQueueThread(buyqueue);
//                ThreadPoolUtil.pool.execute(dealQueue);
                System.out.println(Thread.activeCount());
            }
            //请求放入到队列中，即完成下单请求
            results.put("done", true);
            results.put("msg", "下订单成功");
        } catch (Exception e) {
            results.put("done", false);
            results.put("msg", "下单失败");
            System.out.println(results);
            System.out.println(e);
        } finally {
//            jedisPool.returnResource(jedis);
        }
        return results;

    }
}
